package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SMPackageDAO;
import mwa.cs.dao.ZoneDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS88000Srvl
 */
public class CS88000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private int vnUserId;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS88000Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String vaProcessType = "";
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaProcessType = request.getParameter("process_type");
//		System.voOut.println("vaProcessType = "+vaProcessType);
		if(vaProcessType=="getDataTable"||vaProcessType.equals("getDataTable")){
			getDataTable(request, response);
		}
		else if(vaProcessType=="create"||vaProcessType.equals("create")){
			createPackage(request, response);
		}
		else if(vaProcessType=="update"||vaProcessType.equals("update")){
			updatePackage(request, response);
		}
		else if(vaProcessType=="delete"||vaProcessType.equals("delete")){
			deletePackage(request, response);
		}
	}
	private void deletePackage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException  {
	
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		String vaPackageId = request.getParameter("packageId");
		String vaPackageName = request.getParameter("packageName");
		
		try{
			this.db = new Database();
			db.beginTransaction();
			SMPackageDAO voSmPackageDAO = new SMPackageDAO(db);
			//Check duplicate
			if(voSmPackageDAO.isDuplicate(vaPackageId,"")){
				//Duplicated
				boolean vbResult = voSmPackageDAO.deleteSMPackage(vaPackageId);
				
				if(vbResult){
					voOut.print("Success");
				}
				else{
					voOut.print("Fail");
				}
				
			}
			else{
				//Not duplicated
				voOut.print("Not found");
			}
			db.commit();
		}
		catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS88000", JDate.getDate(), JDate.getTime(),vnUserId, "CS88000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			System.out.println("Error Add SMPackageDAO :"+e);
			voOut.print("Fail");
		}
		finally{
			db.close();
		}
		
	}

	private void updatePackage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException  {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		String vaPackageId = request.getParameter("packageId");
		String vaPackageName = request.getParameter("packageName");
		
		try{
			this.db = new Database();
			db.beginTransaction();
			SMPackageDAO voSmPackageDAO = new SMPackageDAO(db);
			//Check duplicate
			if(voSmPackageDAO.isDuplicate(vaPackageId,vaPackageName)){
				//Duplicated
				boolean vbResult = voSmPackageDAO.updateSMPackage(Integer.toString(vnUserId), vaPackageId, vaPackageName);
				if(vbResult){
					voOut.print("Success");
				}
				else{
					voOut.print("Fail");
				}
				
			}
			else{
				//Not duplicated
				voOut.print("Not Duplicated");
			}
		}
		catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS88000", JDate.getDate(), JDate.getTime(),vnUserId, "CS88000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			System.out.println("Error Add SMPackageDAO :"+e);
			voOut.print("Fail");
		}
		finally{
			db.close();
		}
		
	}

	private void createPackage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		String vaPackageId = request.getParameter("packageId");
		String vaPackageName = request.getParameter("packageName");
		
		try{
			this.db = new Database();
			db.beginTransaction();
			SMPackageDAO smPackageDAO = new SMPackageDAO(db);
			//Check duplicate
			if(smPackageDAO.isDuplicate(vaPackageId,vaPackageName)){
				//Duplicated
				voOut.print("Duplicated");
			}
			else{
				//Not duplicated
				boolean vbResult = smPackageDAO.addSMPackage(Integer.toString(vnUserId), vaPackageId, vaPackageName);
				if(vbResult){
					voOut.print("Success");
				}
				else{
					voOut.print("Fail");
				}
			}
		}
		catch (Exception e) {
			db.rollback();
			SMErrorLogDAO.getInstance().addLog(0, "CS88000", JDate.getDate(), JDate.getTime(),vnUserId, "CS88000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			System.out.println("Error Add SMPackageDAO :"+e);
			voOut.print("Fail");
		}
		finally{
			db.close();
		}
		
		
	}

	public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");

		int vnStart;
		int vnAmount;
		//Test
		if(request.getParameter("iDisplayStart") != null){
			vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
		} else  {
			vnStart = 0;
		}

		if(request.getParameter("iDisplayLength") != null){
			vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		}else{
			vnAmount = 10;
		}
		
		
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		this.db = new Database();
		
		SMPackageDAO voSmPackageDAO = new SMPackageDAO(db);
		
		List<Map<String , Object>> voListFindAll;
		voListFindAll = voSmPackageDAO.findAll(vnStart, vnAmount);
//		System.voOut.println("vnStart = "+vnStart+" , vnAmount = "+vnAmount);
//		System.voOut.println("Result size :"+listFindAll.size());
		vnStart++;
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> voMapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			
			
			voColumn.add(vnStart);
			voColumn.add(voMapItem.get("PACKAGE_ID"));
			voColumn.add(voMapItem.get("PACKAGE_NAME"));
		
			
			String vaStrStatus = "";
			
			if(voMapItem.get("STATUS")=="N"||voMapItem.get("STATUS").equals("N"))
			{
				vaStrStatus = "<div><font color='red'><i class='glyphicon glyphicon-remove'></i></font></div><div><font color='red'>ยังไม่ดำเนินการ</font></div>";
			}
			else
			{
				vaStrStatus = "<div><font color='green'><i class='glyphicon glyphicon-ok'></i></font></div><div><font color='green'>ดำเนินการแล้ว</font></div>";
			}
			
			voColumn.add(vaStrStatus);
			voRow.add(voColumn);
			
			vnStart++;
		}
			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", voSmPackageDAO.countAll());
			voObject.put("aaData", voRow);
			db.close();
		
		  voOut.print(voObject.toJSONString());
	}

}
